package com.Policing;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.Nullable;
import android.util.Base64;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ListView;

import com.Policing.Adapter.Input_Adapter_item;
import com.Policing.Adapter.Partoculayout_Adapter;
import com.Policing.Ip_set.Ip_Set;
import com.Policing.Since_case.Since_case;
import com.Policing.bean.Input_item;
import com.Policing.bean.Issued_bean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hb.dialog.dialog.LoadingDialog;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2019/3/13.
 */

public class Particulars extends Activity {
  private ListView lv;
  private String url;//在用资产
  private String url_stock;//待入库
  private String url_unused;//闲置资产
  private ImageView fh;
  private String url_allot,url_shift;
  private Handler handler = new Handler();
  private String deptid;
  private List<Input_item> data = new ArrayList<>();
  List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
  LoadingDialog loadingDialog;
  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.particulars);
    SharedPreferences mm = getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
    deptid = mm.getString("id","");
    inview();
    url_shift  ="http://"+ Ip_Set.IP+"/api/transferQueryById";
    url_allot  ="http://"+ Ip_Set.IP+"/api/allotQueryById";
    url = "http://"+ Ip_Set.IP+"/api/assetQuery1";
    url_stock = "http://"+ Ip_Set.IP+"/api/assetQuery0";
    url_unused = "http://"+ Ip_Set.IP+"/api/assetQuery";
    Intent intent = getIntent();
    if (intent.getStringExtra("state").equals("1")){
      loadingDialog = new LoadingDialog(this);
      loadingDialog.setMessage("加载中....");
      loadingDialog.show();
      load();
    }else if (intent.getStringExtra("state").equals("2")){
      loadingDialog = new LoadingDialog(this);
      loadingDialog.setMessage("加载中....");
      loadingDialog.show();
      stock_load();
    }else if (intent.getStringExtra("state").equals("3")){
      loadingDialog = new LoadingDialog(this);
      loadingDialog.setMessage("加载中....");
      loadingDialog.show();
      unused_load();
    }else if (intent.getStringExtra("state").equals("4")){
      loadingDialog = new LoadingDialog(this);
      loadingDialog.setMessage("加载中....");
      loadingDialog.show();
      shift_load(intent.getStringExtra("repairsId"));
    }else if (intent.getStringExtra("state").equals("5")){
      loadingDialog = new LoadingDialog(this);
      loadingDialog.setMessage("加载中....");
      loadingDialog.show();
      allot_load(intent.getStringExtra("repairsId"));
    }



  }

  private void shift_load(final String repairsId) {
    new Thread(() -> {
      OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
      FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
      formBody.add("transferId",repairsId)
      .add("source",Since_case.set().getSource());
      Request request = new Request.Builder()//创建Request 对象。
              .url(url_shift)
              .post(formBody.build())//传递请求体
              .build();
      client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
          //回调方法的使用与get异步请求相同
          Log.i("123123", "error");
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
          final String responseData = response.body().string();
          //回调方法的使用与get异步请求相同
          Log.i("123123", responseData);
          handler.post(() -> {
            Bitmap bitmap =null;
            Gson gson = new Gson();
            List<Issued_bean> userList = gson.fromJson(responseData, new TypeToken<List<Issued_bean>>(){}.getType());
            for(int i = 0;i < userList.size();i++){
              String assetName = userList.get(i).getAssetName();
              String deptId = userList.get(i).getDeptId();
              String assetNumber =userList.get(i).getAssetNumber();
              String userId = userList.get(i).getUserId();
              String model = userList.get(i).getModel();
              String type = userList.get(i).getType();
              if (userList.get(i).getImage().equals("")){// getResources().openRawResource(R.mipmap.null_po);
                @SuppressLint("ResourceType") InputStream is = getResources().openRawResource(R.mipmap.null_po);
                bitmap = BitmapFactory.decodeStream(is);
              }else {
                byte [] input = Base64.decode(userList.get(i).getImage(), Base64.DEFAULT);
                bitmap = BitmapFactory.decodeByteArray(input, 0, input.length);
              }
              data.add(new Input_item(bitmap,assetName,deptId,assetNumber,userId,model,type,""));
            }
            Input_Adapter_item adapter_item = new Input_Adapter_item(Particulars.this,R.layout.input_adapter_item,data);
            lv.setAdapter(adapter_item);
            loadingDialog.dismiss();



          });

        }
      });

    }).start();
  }
  private void allot_load(final String repairsId) {
    new Thread(() -> {
      OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
      FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
      formBody.add("allotId",repairsId)
              .add("source", Since_case.set().getSource());
      Request request = new Request.Builder()//创建Request 对象。
              .url(url_allot)
              .post(formBody.build())//传递请求体
              .build();
      client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
          //回调方法的使用与get异步请求相同
          Log.i("123123", "error");
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
          final String responseData = response.body().string();
          //回调方法的使用与get异步请求相同
          Log.i("123123", responseData);
          handler.post(() -> {
            Bitmap bitmap =null;
            Gson gson = new Gson();
            List<Issued_bean> userList = gson.fromJson(responseData, new TypeToken<List<Issued_bean>>(){}.getType());
            for(int i = 0;i < userList.size();i++){
              String assetName = userList.get(i).getAssetName();
              String deptId = userList.get(i).getDeptId();
              String assetNumber =userList.get(i).getAssetNumber();
              String userId = userList.get(i).getUserId();
              String model = userList.get(i).getModel();
              String type = userList.get(i).getType();
              if (userList.get(i).getImage().equals("")){
               /* InputStream is = getResources().openRawResource(R.mipmap.null_po);
                bitmap = BitmapFactory.decodeStream(is);*/
              }else {
                byte [] input = Base64.decode(userList.get(i).getImage(), Base64.DEFAULT);
                bitmap = BitmapFactory.decodeByteArray(input, 0, input.length);
              }
              data.add(new Input_item(bitmap,assetName,deptId,assetNumber,userId,model,type,""));
            }
            Input_Adapter_item adapter_item = new Input_Adapter_item(Particulars.this,R.layout.input_adapter_item,data);
            lv.setAdapter(adapter_item);
            loadingDialog.dismiss();
          });

        }
      });

    }).start();
  }
  private void unused_load() {
    new Thread(){
      @Override
      public void run() {
        try {
          OkHttpClient client = new OkHttpClient();
          RequestBody requestBody = new FormBody.Builder()
                  .add("id",deptid)
                  .add("source",Since_case.set().getSource())
                  .build();
          Request request = new Request.Builder()
                  .url(url_unused)
                  .post(requestBody).build();
          Response response = client.newCall(request).execute();
          String responseData = response.body().string();
          Log.i("222",responseData);
          showResponse_unused(responseData);//解析

        } catch (IOException e) {
          e.printStackTrace();

        }


      }
    }.start();
  }

  private void showResponse_unused(final String responseData) {
    runOnUiThread(() -> {
      Bitmap bitmap =null;
      Gson gson = new Gson();
      List<Issued_bean> userList = gson.fromJson(responseData, new TypeToken<List<Issued_bean>>(){}.getType());
      for(int i = 0;i < userList.size();i++){
        String assetName = userList.get(i).getAssetName();
        String deptId = userList.get(i).getDeptId();
        String assetNumber =userList.get(i).getAssetNumber();
        String userId = userList.get(i).getUserId();
        String model = userList.get(i).getModel();
        String type = userList.get(i).getType();
        if (userList.get(i).getImage().equals("")){
          /*InputStream is = getResources().openRawResource(R.mipmap.null_po);
          bitmap = BitmapFactory.decodeStream(is);*/
        }else {
          byte [] input = Base64.decode(userList.get(i).getImage(), Base64.DEFAULT);
          bitmap = BitmapFactory.decodeByteArray(input, 0, input.length);
        }
        data.add(new Input_item(bitmap,assetName,deptId,assetNumber,userId,model,type,""));
      }
      Input_Adapter_item adapter_item = new Input_Adapter_item(Particulars.this,R.layout.input_adapter_item,data);
      lv.setAdapter(adapter_item);
      loadingDialog.dismiss();

    });
  }

  private void stock_load() {
    new Thread(){
      @Override
      public void run() {
        try {
          OkHttpClient client = new OkHttpClient();
          RequestBody requestBody = new FormBody.Builder()
                  .add("id",deptid)
                  .add("source",Since_case.set().getSource())
                  .build();
          Request request = new Request.Builder()
                  .url(url_stock)
                  .post(requestBody).build();
          Response response = client.newCall(request).execute();
          String responseData = response.body().string();
          Log.i("222",responseData);
          showResponse_stock(responseData);//解析

        } catch (IOException e) {
          e.printStackTrace();

        }


      }
    }.start();
  }

  private void showResponse_stock(final String responseData) {
    runOnUiThread(() -> {
      Bitmap bitmap =null;
      Gson gson = new Gson();
      List<Issued_bean> userList = gson.fromJson(responseData, new TypeToken<List<Issued_bean>>(){}.getType());
      for(int i = 0;i < userList.size();i++){
        String assetName = userList.get(i).getAssetName();
        String deptId = userList.get(i).getDeptId();
        String assetNumber =userList.get(i).getAssetNumber();
        String userId = userList.get(i).getUserId();
        String model = userList.get(i).getModel();
        String type = userList.get(i).getType();
        if (userList.get(i).getImage().equals("")){
          /*InputStream is = getResources().openRawResource(R.mipmap.null_po);
          bitmap = BitmapFactory.decodeStream(is);*/
        }else {
          byte [] input = Base64.decode(userList.get(i).getImage(), Base64.DEFAULT);
          bitmap = BitmapFactory.decodeByteArray(input, 0, input.length);
        }
        data.add(new Input_item(bitmap,assetName,deptId,assetNumber,userId,model,type,""));
      }
      Input_Adapter_item adapter_item = new Input_Adapter_item(Particulars.this,R.layout.input_adapter_item,data);
      lv.setAdapter(adapter_item);
      loadingDialog.dismiss();
    });
  }

  private void load() {
    new Thread(){
      @Override
      public void run() {
        try {
          OkHttpClient client = new OkHttpClient();
          RequestBody requestBody = new FormBody.Builder()
                  .add("id",deptid)
                  .add("source",Since_case.set().getSource())
                  .build();
          Request request = new Request.Builder()
                  .url(url)
                  .post(requestBody).build();
          Response response = client.newCall(request).execute();
          String responseData = response.body().string();
          Log.i("222",responseData);
          showResponse(responseData);//解析

        } catch (IOException e) {
          e.printStackTrace();

        }


      }
    }.start();
  }

  private void showResponse(final String responseData) {
    runOnUiThread(() -> {
      Bitmap bitmap =null;
      Gson gson = new Gson();
      List<Issued_bean> userList = gson.fromJson(responseData, new TypeToken<List<Issued_bean>>(){}.getType());
      for(int i = 0;i < userList.size();i++){
        String assetName = userList.get(i).getAssetName();
        String deptId = userList.get(i).getDeptId();
        String assetNumber =userList.get(i).getAssetNumber();
        String userId = userList.get(i).getUserId();
        String model = userList.get(i).getModel();
        String type = userList.get(i).getType();
        if (userList.get(i).getImage().equals("")){
          /*InputStream is = getResources().openRawResource(R.mipmap.null_po);
          bitmap = BitmapFactory.decodeStream(is);*/
        }else {
          byte [] input = Base64.decode(userList.get(i).getImage(), Base64.DEFAULT);
          bitmap = BitmapFactory.decodeByteArray(input, 0, input.length);
        }
        data.add(new Input_item(bitmap,assetName,deptId,assetNumber,userId,model,type,""));
      }
      Partoculayout_Adapter adapter_item = new Partoculayout_Adapter(Particulars.this,R.layout.particulars_item,data);
      lv.setAdapter(adapter_item);
      loadingDialog.dismiss();
    });
  }

  private void inview() {
    fh = (ImageView) findViewById(R.id.fh);
    fh.setOnClickListener(v -> finish());
    lv = (ListView) findViewById(R.id.particulars_lv);
  }



}
